package wordapp;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.swing.JOptionPane;

/**
 *
 * @author Randall Schmidt
 */
public class ConnectionManager {
    
    private static String url = "http://api.microsofttranslator.com/V2/Http.svc/Translate";
    private static String charset = "UTF-8";
    private static String param1 = "appid";
    private static String param1_lit = "AA7A5FF13B19BD8F7E8B922F248762DB10791270";
    private static String param2 = "text";
    private static String param3 = "to";
    private static String param4 = "contentType";
    private static String param4_lit = "text/plain";
    private static String param5 = "from";
    
    
    public static String translate(String lang_from, String lang_to, String text)
    {
        String query = param1 + "=" + param1_lit + "&" + param2 + "=" + URLEncoder.encode(text) + "&" + param3 + "=" + lang_to + "&" + param4 + "=" + param4_lit + "&" + param5 + "=" + lang_from; 
        URLConnection connection;
        String response_str = null;
        try 
        {
            connection = new URL(url + "?" + query).openConnection();
            connection.setRequestProperty("Accept-Charset", charset);
            InputStream response;
            response = connection.getInputStream();
            response_str = convertStreamToString(response);
            response_str = response_str.substring(response_str.indexOf(">") + 1);
            response_str = response_str.substring(0, response_str.indexOf("<"));          
        } 
        catch (Exception ex) 
        {
            JOptionPane.showMessageDialog(App.app, "Possibly failed to connect to Bing language services. Please try again or report this error.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        
        return response_str;
    }
    
    public static String convertStreamToString(java.io.InputStream is) 
    {
        try 
        {
            return new java.util.Scanner(is).useDelimiter("\\A").next();
        } 
        catch (java.util.NoSuchElementException e) 
        {
            return "";
        }
    }
}
